package com.ydgk.servlet;

import com.ydgk.bean.Admin;
import com.ydgk.dao.AdminDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet(name = "CookieLoginServlet", urlPatterns = "/CookieLoginServlet.action")
public class CookieLoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        Admin admin = new Admin();
        AdminDao adminDao = new AdminDao();
        HttpSession session = request.getSession();
        String cookiename = request.getParameter("cookiename");
        String cookiepass = request.getParameter("cookiepass");
        admin.setAname(cookiename);
        admin.setApass(cookiepass);
        Admin newAdmin = adminDao.login(admin);
        if(newAdmin!=null){
            session.setAttribute("admin",newAdmin);
            response.sendRedirect(request.getContextPath()+"/home.jsp");
        }else{
            Cookie cookieName = new Cookie("aname",admin.getAname());
            Cookie cookiePass = new Cookie("apass",admin.getApass());
            cookieName.setMaxAge(0);
            cookiePass.setMaxAge(0);
            response.addCookie(cookieName);
            response.addCookie(cookiePass);
            response.sendRedirect(request.getContextPath()+"/login.jsp?msg='erro'");
        }

    }
}
